﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace AMM.CustomWinControls {
    public partial class CheckedListBoxDropDownEx : DropDownControlEx {

        #region Properties

        public int HeightEx { get; set; }
        public string ButtonTextEx { get; set; }
        public List<string> ItemsEx { get; set; }
        public List<string> SelectedItemsEx { get; set; }

        #endregion

        public event EventHandler ValueChanged;
        
        public CheckedListBoxDropDownEx() {
            InitializeComponent();
        }

        protected virtual void OnValueChanged(EventArgs eventargs) {
            this.ValueEx = string.Join(";", this.SelectedItemsEx.ToArray());
            if (this.ValueChanged != null) {
                this.ValueChanged(this, eventargs);
            }
        }

        private void CheckedListBoxDropDownEx_Load(object sender, EventArgs e) {
            this.HeightEx = this.HeightEx == 0 ? 121 : this.HeightEx;
            this.pnlContainer.Width = this.Width - 2;
            this.pnlContainer.Height = this.HeightEx;
            this.btnSelected.Text = string.IsNullOrEmpty(this.ButtonTextEx) ? "Selected" : this.ButtonTextEx;
            this.btnSelected.Click += new EventHandler(btnSelected_Click);
            if (this.ItemsEx != null) {
                this.clbList.Items.AddRange(this.ItemsEx.ToArray());
                this.clbList.CheckOnClick = true;
            }
            this.SelectedItemsEx = new List<string>();
            this.DropDownShowed += new EventHandler(CheckedListBoxDropDownEx_DropDownShowed);
            this.InitializeDropDownEx(this.pnlContainer);
        }

        void CheckedListBoxDropDownEx_DropDownShowed(object sender, EventArgs e) {
            if (this.ValueEx != null && !string.IsNullOrEmpty(this.ValueEx.ToString())) {
                this.SelectedItemsEx = this.ValueEx.ToString().Split(';').ToList();
            }
            for (int i = 0; i < this.clbList.Items.Count; i++) {
                this.clbList.SetItemChecked(i, this.SelectedItemsEx.Contains(this.clbList.Items[i].ToString()));
            }
            this.SelectedItemsEx.Clear();
        }

        void btnSelected_Click(object sender, EventArgs e) {
            for (int i = 0; i < this.clbList.CheckedItems.Count; i++) {
                this.SelectedItemsEx.Add(this.clbList.CheckedItems[i].ToString());
            }
            this.OnValueChanged(e);
            this.CloseDropDownEx();
        }

    }
}
